use std::io::{Write, Read}; // 移除了self
use std::net::TcpStream;
use std::thread;
use std::time::Duration;

fn main() {
    let server = "127.0.0.1:12345";
    // 注意这里的mut关键字，它使得stream变为可变
    let mut stream = TcpStream::connect(server).expect("无法连接到服务器");

    let handle = thread::spawn(move || {
        let mut buffer = [0; 1024];
        loop {
            match stream.read(&mut buffer) {
                Ok(n) => {
                    if n > 0 {
                        print!("从服务器收到: {}", String::from_utf8_lossy(&buffer[..n]));
                    }
                }
                Err(_) => break, // 连接关闭或发生错误时退出循环
            }
        }
    });
    let message = "Hello, Server!";
    stream.write_all(message.as_bytes()).expect("无法发送消息到服务器");
    stream.flush().expect("无法刷新缓冲区");
    thread::sleep(Duration::from_secs(5));
    stream.shutdown(std::net::Shutdown::Both).expect("无法关闭连接");
    handle.join().expect("子线程发生错误");
}